package cn.yuanqiao.web.controller.manage;

import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.manage.domain.ManageTenant;
import cn.yuanqiao.manage.service.IManageTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 租户信息Controller
 *
 * @author yuanqiao
 * @date 2023-06-07
 */
@RestController
@RequestMapping("/manage/tenant")
public class ManageTenantController extends BaseController
{
    @Autowired
    private IManageTenantService manageTenantService;

    /**
     * 查询租户信息列表
     */
    //@RequiresPermissionsmissions("tenantManage:infoManage:query")
    @Log(title = "租户信息管理列表查询",businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(ManageTenant manageTenant)
    {
        startPage();
        List<ManageTenant> list = manageTenantService.selectManageTenantList(manageTenant);
        return getDataTable(list);
    }

    ////@RequiresPermissionsmissions("manage:tenant:listOption")
    @GetMapping("/listOption")
    public AjaxResult listOption(ManageTenant manageTenant)
    {
        manageTenant.setState("0");
        List<ManageTenant> list = manageTenantService.selectManageTenantList(manageTenant);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("tenantOptions",list);
        return ajax;
    }
    /**
     * 导出租户信息列表
     */
    //@RequiresPermissionsmissions("manage:tenant:export")
    @Log(title = "导出租户信息列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ManageTenant manageTenant)
    {
        List<ManageTenant> list = manageTenantService.selectManageTenantList(manageTenant);
        ExcelUtil<ManageTenant> util = new ExcelUtil<ManageTenant>(ManageTenant.class);
        util.exportExcel(response, list, "租户信息数据");
    }

    /**
     * 获取租户信息详细信息
     */
    //@RequiresPermissionsmissions("manage:tenant:query")
    @Log(title = "获取租户信息详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") String ID)
    {
        return success(manageTenantService.selectManageTenantByID(ID));
    }

    /**
     * 新增租户信息
     */
    //@RequiresPermissionsmissions("manage:tenant:add")
    @Log(title = "新增租户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ManageTenant manageTenant)
    {
        return toAjax(manageTenantService.insertManageTenant(manageTenant));
    }

    /**
     * 修改租户信息
     */
    //@RequiresPermissionsmissions("manage:tenant:edit")
    @Log(title = "修改租户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ManageTenant manageTenant)
    {
        return toAjax(manageTenantService.updateManageTenant(manageTenant));
    }
    //@RequiresPermissionsmissions("manage:tenant:edit")
    @Log(title = "修改租户状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult editStatus(@RequestBody ManageTenant manageTenant)
    {
        return toAjax(manageTenantService.updateManageTenantStatus(manageTenant));
    }

    /**
     * 删除租户信息
     */
    ////@RequiresPermissionsmissions("manage:tenant:remove")
    @Log(title = "删除租户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(manageTenantService.deleteManageTenantByIDs(IDs));
    }

    @Log(title = "导入租户信息模板下载", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<ManageTenant> util = new ExcelUtil<ManageTenant>(ManageTenant.class);
        util.importTemplateExcel(response, "租户数据");
    }

    //@RequiresPermissionsmissions("manage:tenant:import")
    @Log(title = "导入租户信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ManageTenant> util = new ExcelUtil<>(ManageTenant.class);

        //List<ManageTenant> userList = util.importExcel(file.getInputStream());

        InputStream in=file.getInputStream();
        List<ManageTenant> userList = util.importExcel(in);
        in.close();
        String operName = SecurityUtils.getUsername();
        String message = manageTenantService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @GetMapping("/info/{loginName}")
    public R<LoginUser> info(@PathVariable("loginName") String loginName)
    {
        ManageTenant manageTenant = manageTenantService.selectUserByLoginName(loginName);
        if (StringUtils.isNull(manageTenant))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        /*Set<String> roles = new HashSet<>();
        roles.add(SysContants.MANAGEROLEFLAG);
        // 权限集合
        R<String> menuPermission = remoteUserService.getMenuPermission(SysContants.MANAGEROLEFLAG);
        String data = menuPermission.getData();


        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);*/
        return null;
    }

    @GetMapping("/stateInfo/{tenantCode}")
    public R<String> stateInfo(@PathVariable("tenantCode") String tenantCode)
    {
        ManageTenant manageTenant1 = new ManageTenant();
        manageTenant1.setTenantCode(tenantCode);
        List<ManageTenant> manageTenants = manageTenantService.selectManageTenantList(manageTenant1);
        ManageTenant manageTenant2 = manageTenants.get(0);
        String state = manageTenant2.getState();
        return R.ok(state);
    }

    @GetMapping("/needInit")
    R<Boolean> needInit(@RequestParam("tenantCode") String tenantCode){
        Boolean bl = false;
        if(StringUtils.isNotEmpty(tenantCode)){
            //验证门类表是否存在
            String tableName = (tenantCode+"_CATEGORY").toUpperCase();
            int num = manageTenantService.isExistTable(tableName);
            if(num == 0){
                bl = true;
            }
        }
        return R.ok(bl);
    }

    @GetMapping("/getTenantCodeManagerDept")
    R<String> getTenantCodeManagerDept(){
        ManageTenant manageTenant = manageTenantService.selectTenantByManager("true");
        return R.ok(manageTenant == null ? null:manageTenant.getTenantCode());
    }

}
